package cn.tedu.mvcboottest.common.exception;

import cn.tedu.mvcboottest.common.response.JsonResult;
import cn.tedu.mvcboottest.common.response.StatuCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
@Validated
public class GlobalExceptionhandler {
    @ExceptionHandler
    public JsonResult dohandlerIllegalArgumentException(IllegalArgumentException ex){
        String data=ex.getMessage();
        log.debug("IllegalArgumentException:"+data);
        return JsonResult.fail(data);
    }
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data=ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:"+data);
        return new JsonResult(StatuCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex){
        String data=ex.getMessage().split(":")[1].trim();
        log.debug("ConstraintViolationException:"+data);
        return new JsonResult(StatuCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandlerRuntimeException(RuntimeException ex){
        String data=ex.getMessage();
        log.error("RuntimeException:"+data);
        return JsonResult.fail(data);
    }
    @ExceptionHandler
    public JsonResult doThrowable(Throwable tw){
        String data=tw.getMessage();
        log.error("Exception:"+data);
        return new JsonResult(StatuCode.VALIDATED_ERROR,data);
    }
}
